package com.nsgf.library.ui.page.manager;

import static com.nsgf.library.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.gson.Gson;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WeatherBean;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNsgfManagerWorkOrderBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.matisse.Matisse;
import com.nsgf.library.photopicker.PhotoPicker;
import com.nsgf.library.photopicker.utils.PermissionsUtils;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.ui.adapter.WeatherListAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.FileUploader;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.SPUtil;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import io.reactivex.disposables.Disposable;


public class ManagerWorkOrderDetailsActivity extends BaseActivity {

    ManagerWorkOrderDetailsStates states;

    AccountRequester accountRequester;

    private WeatherListAdapter mAdapter;

    public static final String LOCAL_WORK_ORDER_DETAIL = "workOrderDetail";//开始巡查本地存储

    public static final String LOCAL_WORK_ORDER_FORM = "workOrderForm";//开始巡查本地存储form表单提交内容

    private String orderCode = "";//工单编号

    @Override
    protected void initViewModel() {

        states = getActivityScopeViewModel(ManagerWorkOrderDetailsStates.class);
        accountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new WeatherListAdapter(this);
        return new DataBindingConfig(R.layout.activity_nsgf_manager_work_order, BR.vm, states)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private ActivityNsgfManagerWorkOrderBinding mBinding;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(accountRequester);

        orderCode = getIntent().getStringExtra("orderCode");

        accountRequester.getDictItems("weather.type");
        accountRequester.getWeatherDetailResult().observe(this, new Observer<DataResult<WeatherBean>>() {
            @Override
            public void onChanged(DataResult<WeatherBean> dataResult) {

                if (dataResult.getResponseStatus().isSuccess()) {
                    if (200 == dataResult.getResult().getCode()) {
                        states.weatherList.set(dataResult.getResult().getData());
                    } else {

                        if (401 == dataResult.getResult().getCode()) {
                            UserInfo.getInstance().clearUserInfo();
                            finish();
                        }
                        ToastUtils.showLongToast(dataResult.getResult().getMsg());
                    }
                } else {
                    ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
                }
            }
        });

        mBinding = (ActivityNsgfManagerWorkOrderBinding) getBinding();

        mBinding.multiPickResultView.init(this, MultiPickResultView.ACTION_SELECT, new ArrayList<>(), 5);


        String orderFrom = SPUtil.get(orderCode, LOCAL_WORK_ORDER_FORM, "", this);

        String workOrderDetail = SPUtil.get(orderCode, LOCAL_WORK_ORDER_DETAIL, "", this);

        // 表单 和 工单详情必须都不为空时直接进入巡查
        if (!StringUtil.isEmpty(orderFrom) && !StringUtil.isEmpty(workOrderDetail)) {
            workOrderDetailBean = gson.fromJson(orderFrom, WorkOrderDetailBean.class);
            workOrderDetailLocal = gson.fromJson(workOrderDetail, WorkOrderDetailBean.DataBean.class);
            startActivity(new Intent()
                    .putExtra("title", workOrderDetailLocal.getPatrolTypeDesc())
                    .putExtra("bean", (Parcelable) workOrderDetailLocal)
                    .setClass(ManagerWorkOrderDetailsActivity.this,
                            ManagerWorkOrderDamDetailsActivity.class));
            finish();
        }

        accountRequester.patrolDetail(orderCode);
        accountRequester.getWorkOrderDetail().observe(this, dataResult -> {


            if (dataResult.getResponseStatus().isSuccess()) {
                if (200 == dataResult.getResult().getCode()) {
                    states.detailBeanState.set(dataResult.getResult().getData());
                    states.titleBar.set(dataResult.getResult().getData().getPatrolTypeDesc());
                    workOrderDetailLocal = dataResult.getResult().getData();
                } else {
                    if (401 == dataResult.getResult().getCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        finish();
                    }
                    ToastUtils.showLongToast(dataResult.getResult().getMsg());
                }
            } else {
                ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
                finish();
            }
        });

        accountRequester.getFileInfo().observe(this, responseStatusDataResult -> {
            fileDto.clear();
            fileDto.add(responseStatusDataResult.getResult().getData());
        });


        mAdapter.setOnItemClickListener((viewId, item, position) -> {
            for (int i = 0; i < mAdapter.getCurrentList().size(); i++) {
                mAdapter.getCurrentList().get(i).setSelectWeather(false);
            }
            mAdapter.getCurrentList().get(position).setSelectWeather(true);
            mAdapter.notifyDataSetChanged();
        });


    }

    public static class ManagerWorkOrderDetailsStates extends StateHolder {

        public final State<String> name = new State<>("");
        public final State<WorkOrderDetailBean.DataBean> detailBeanState = new State<WorkOrderDetailBean.DataBean>(null);
        public final State<List<WeatherBean.DataBean>> weatherList = new State<List<WeatherBean.DataBean>>(null);

        public final State<Boolean> loadingVisible = new State<>(false);

    }

    private WorkOrderDetailBean.DataBean.BuProjectDailyBean buProjectDailyBean = new WorkOrderDetailBean.DataBean.BuProjectDailyBean();

    List<WorkOrderDetailBean.FileDto> fileDto = new ArrayList<>();

    /**
     * 工单提交处理参数
     */
    WorkOrderDetailBean workOrderDetailBean = new WorkOrderDetailBean();

    /**
     * 详情本地存储
     */
    WorkOrderDetailBean.DataBean workOrderDetailLocal;

    WorkOrderDetailBean.DataBean dataBean = new WorkOrderDetailBean.DataBean();
    // 创建Gson对象
    Gson gson = new Gson();
    private String json;

    private int upLoadNumber = 0;

    public class ClickProxy {

        public void login() {

            buProjectDailyBean.setWaterLevel(mBinding.etNsgfManagerCapacity.getText().toString());
            buProjectDailyBean.setRainfall(mBinding.etNsgfManagerRainfall.getText().toString());
            for (WeatherBean.DataBean itemsBean : mAdapter.getCurrentList()) {
                if (itemsBean.isSelectWeather()) {
                    buProjectDailyBean.setWeather(itemsBean.getItemValue());
                }
            }
            if (StringUtil.isEmpty(buProjectDailyBean.getWeather())
                    || StringUtil.isEmpty(buProjectDailyBean.getWaterLevel())
                    || StringUtil.isEmpty(buProjectDailyBean.getRainfall())
                    || mBinding.multiPickResultView.getPhotos().isEmpty()) {
                ToastUtils.showLongToast("请完善巡检信息");
                return;
            }
            dataBean.setBuProjectDaily(buProjectDailyBean);

            if (!mBinding.multiPickResultView.getPhotos().isEmpty()) {
                fileDto.clear();
                getController().displayLoading();
                for (WorkOrderDetailBean.FileDto path : mBinding.multiPickResultView.getPhotos()) {
                    DataRepository.getInstance().uploadFile(path.getFilePath()).subscribe(new io.reactivex.Observer<DataResult<ResponseStatus<WorkOrderDetailBean.FileDto>>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(DataResult<ResponseStatus<WorkOrderDetailBean.FileDto>> dataResult) {

                            if (dataResult.getResponseStatus().isSuccess()) {
                                if (200 == dataResult.getResult().getResponseCode()) {
                                    fileDto.add(dataResult.getResult().getData());
                                    if (mBinding.multiPickResultView.getPhotos().size() == fileDto.size()) {
                                        dataBean.setSafetyPhotoList(fileDto);
                                        // 记录第一次巡检时间
                                        Calendar calendar = Calendar.getInstance();
                                        dataBean.setStartHandleTime(Kits.Date.getYmdhmss(calendar.getTimeInMillis()));
                                        states.detailBeanState.get().setStartHandleTime(Kits.Date.getYmdhmss(calendar.getTimeInMillis()));
                                        workOrderDetailBean.setData(dataBean);
                                        // 将Java实体类转换为json字符串
                                        SPUtil.put(orderCode, LOCAL_WORK_ORDER_FORM, gson.toJson(workOrderDetailBean), ManagerWorkOrderDetailsActivity.this);
                                        SPUtil.put(orderCode, LOCAL_WORK_ORDER_DETAIL, gson.toJson(workOrderDetailLocal), ManagerWorkOrderDetailsActivity.this);

                                        if (null != states.detailBeanState.get()) {
                                            startActivity(new Intent()
                                                    .putExtra("title", Objects.requireNonNull(states.detailBeanState.get()).getPatrolTypeDesc())
                                                    .putExtra("bean", (Parcelable) states.detailBeanState.get())
                                                    .setClass(ManagerWorkOrderDetailsActivity.this,
                                                            ManagerWorkOrderDamDetailsActivity.class));
                                        }
                                        finish();
                                    }

                                } else {
                                    ToastUtils.showShortToast(dataResult.getResult().getMsg());
                                }

                            } else {
                                getController().dismissLoading();
                                Error(dataResult.getResponseStatus().getE());
                            }

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
                }
            }

        }

        public void path() {

            boolean checkPermissionFirst;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                checkPermissionFirst = PermissionsUtils.checkPermissionFirst(ManagerWorkOrderDetailsActivity.this, 10003,
                        new String[]{Manifest.permission.READ_MEDIA_IMAGES,
                                Manifest.permission.READ_MEDIA_VIDEO,
                                Manifest.permission.READ_MEDIA_AUDIO});
            } else
                checkPermissionFirst = PermissionsUtils.checkPermissionFirst(ManagerWorkOrderDetailsActivity.this, 10003,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA});

            if (checkPermissionFirst) {
                PhotoPicker.builder()
                        .setPhotoCount(1)
                        .setGridColumnCount(3)
                        .start(ManagerWorkOrderDetailsActivity.this);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (PhotoPicker.REQUEST_CODE == requestCode) {
                ArrayList<WorkOrderDetailBean.FileDto> photos = new ArrayList<>();
                for (String src : Matisse.obtainPathResult(data)) {
                    WorkOrderDetailBean.FileDto dto = new WorkOrderDetailBean.FileDto();
                    dto.setFilePath(src);
                    photos.add(dto);
                }
                data.putExtra(KEY_SELECTED_PHOTOS, photos);
                mBinding.multiPickResultView.onActivityResult(requestCode, resultCode, data);
            }
        }
    }
}
